#include "OffLineRenderPCH.h"
#include "OR_ScenePrimitiveTransformed.h"
#include "OR_Intersection.h"

using namespace Utility;
using namespace OffLineRender;

//----------------------------------------------------------------------------
UT_BBOX_AABB OR_ScenePrimitiveTransformed::GetWorldBound() const
{
	return m_kWorldToPrimitive.MotionBounds(m_spScenePrimitive->GetWorldBound(),true);
}
//----------------------------------------------------------------------------
bool OR_ScenePrimitiveTransformed::Intersect(const UT_Ray &r,OR_Intersection *isect) const 
{
	UT_Transform w2p;
	m_kWorldToPrimitive.Interpolate(r.time, &w2p);
	UT_Ray ray = w2p(r);
	
	if (!m_spScenePrimitive->Intersect(ray, isect))
		return false;

	r.maxt = ray.maxt;
	isect->m_uiPrimitiveId = m_uiPrimitiveId;
	
	if (!w2p.IsIdentity())
	{
		// Compute world-to-object transformation for instance
		isect->m_kWorldToObject = isect->m_kWorldToObject * w2p;
		isect->m_kObjectToWorld = UT_MathHelper::Inverse(isect->m_kWorldToObject);

		// Transform instance's differential geometry to world space
		UT_Transform PrimitiveToWorld = UT_MathHelper::Inverse(w2p);
		isect->m_kDifferentialGeometry.p	= PrimitiveToWorld(isect->m_kDifferentialGeometry.p);
		isect->m_kDifferentialGeometry.nn	= UT_MathHelper::Normalize(PrimitiveToWorld(isect->m_kDifferentialGeometry.nn));
		isect->m_kDifferentialGeometry.dpdu	= PrimitiveToWorld(isect->m_kDifferentialGeometry.dpdu);
		isect->m_kDifferentialGeometry.dpdv	= PrimitiveToWorld(isect->m_kDifferentialGeometry.dpdv);
		isect->m_kDifferentialGeometry.dndu	= PrimitiveToWorld(isect->m_kDifferentialGeometry.dndu);
		isect->m_kDifferentialGeometry.dndv	= PrimitiveToWorld(isect->m_kDifferentialGeometry.dndv);
	}
	return true;
}
//----------------------------------------------------------------------------
bool OR_ScenePrimitiveTransformed::IntersectP(const UT_Ray &r) const 
{
	UT_Ray ray;
	m_kWorldToPrimitive(r,&ray);
	return m_spScenePrimitive->IntersectP(ray);
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------